package com.lh_travel.lohas.activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.Toolbar;
import android.transition.Fade;
import android.transition.Transition;
import android.view.View;

import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.OvershootInterpolator;
import android.view.animation.ScaleAnimation;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lh_travel.lohas.R;
import com.lh_travel.lohas.activity.user.LoginActivity;
import com.lh_travel.lohas.adapter.MyFragmentAdapter;
import com.lh_travel.lohas.animation.ScaleXPageTransformer;
import com.lh_travel.lohas.base.api;
import com.lh_travel.lohas.base.baseActivity;
import com.lh_travel.lohas.domain.Comment;
import com.lh_travel.lohas.domain.CommentIntentBean;
import com.lh_travel.lohas.domain.DafultMessageEvent;
import com.lh_travel.lohas.domain.HotelDetail;
import com.lh_travel.lohas.domain.UserBean;
import com.lh_travel.lohas.domain.respon;
import com.lh_travel.lohas.fragment.InfoFragment;
import com.lh_travel.lohas.fragment.PriceFragment;
import com.lh_travel.lohas.fragment.WebFragment;
import com.lh_travel.lohas.interfaces.VPSet;
import com.lh_travel.lohas.utils.FloImageLoader;
import com.lh_travel.lohas.utils.Preferences;
import com.lh_travel.lohas.widget.ShareDialog;
import com.lh_travel.lohas.widget.SharePlatform;
import com.tamic.novate.Throwable;
import com.tamic.novate.callback.RxResultCallback;
import com.tamic.novate.callback.RxStringCallback;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;

import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * Created by aaron on 2018/6/25.
 */

public class HotelDetailActivity extends baseActivity {

    private Banner banner;
    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager vp_content;
    private AppBarLayout appbar;
    private LinearLayout ll_star_container;
    private TextView tv_title;
    private CommentIntentBean bean;
    private ImageButton img_fav;
    private ImageButton img_back;
    private HotelDetail detail;
    private int star;
    private String strStar;
    private ProgressBar pro;
    private NestedScrollView nestedScrollView;
    private UserBean userBean;
    private Comment collectBean;
    private RelativeLayout rl_content;
    private CoordinatorLayout main_content;
    private WebFragment webFragment;
    private MyFragmentAdapter mAdapter;
    private ImageButton img_share;
    private ShareDialog shareDialog;
    private SharePlatform sharePlatform;
    private String share_url;
    private String shared_img_url;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        EventBus.getDefault().register(this);

        setContentView(R.layout.activity_hotel_detail);

        findView();
        bindListner();
        ensureUI();
    }

    @Override
    public void findView() {
        banner = (Banner) findViewById(R.id.banner);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        vp_content = (ViewPager) findViewById(R.id.vp_content);
        appbar = (AppBarLayout) findViewById(R.id.appbar);
        ll_star_container = (LinearLayout) findViewById(R.id.ll_star_container);
        tv_title = (TextView) findViewById(R.id.tv_title);
        img_fav = (ImageButton) findViewById(R.id.img_fav);
        img_back = (ImageButton) findViewById(R.id.img_back);
        pro = (ProgressBar) findViewById(R.id.pro);
        img_share = (ImageButton) findViewById(R.id.img_share);
        main_content = (CoordinatorLayout) findViewById(R.id.main_content);
        nestedScrollView = (NestedScrollView) findViewById(R.id.nestedScrollView);
    }

    @Override
    public void bindListner() {

        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                finish();
            }
        });

        img_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final String title = mContext.getString(R.string.share_title);

                sharePlatform = new SharePlatform(mContext);

                shareDialog.setOnCancleListener(new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        shareDialog.dismiss();
                    }
                });

                shareDialog.setOnWeChatShare(new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        sharePlatform.share(Wechat.NAME, bean.keyWord, title, shared_img_url, share_url);
                        shareDialog.dismiss();
                    }
                });

                shareDialog.setOnWeChatFriendShare(new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        sharePlatform.share(WechatMoments.NAME, bean.keyWord, title, shared_img_url, share_url);
                        shareDialog.dismiss();
                    }
                });

                shareDialog.setOnQQShare(new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        sharePlatform.share(QQ.NAME, bean.keyWord, title, shared_img_url, share_url);
                        shareDialog.dismiss();
                    }
                });

                shareDialog.show();
            }
        });

        img_fav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                userBean = mApp.getBeanPrefernce(Preferences.LOCAL.USERLOGIN);

                if (userBean == null) {

                    Intent intent = new Intent(mContext, LoginActivity.class);

                    startActivity(intent);

                    overridePendingTransition(R.anim.act_bottom_in, R.anim.act_tm2);

                } else {

                    if (collectBean != null) {

                        if (collectBean.is_collect == 1) {

                            new api(mContext).collectDel(HotelDetailActivity.this.userBean.token, bean.id, new RxStringCallback() {
                                @Override
                                public void onNext(Object tag, String response) {
                                    respon result = new Gson().fromJson(response, new TypeToken<respon>() {
                                    }.getType());

                                    if (result.code.equals("200")) {
                                        //改变星星的状态

                                        ScaleAnimation scaleExit = new ScaleAnimation(1f, 0.5f, 1f, 0.5f);
                                        scaleExit.setDuration(300);

                                        scaleExit.setAnimationListener(new Animation.AnimationListener() {
                                            @Override
                                            public void onAnimationStart(Animation animation) {

                                            }

                                            @Override
                                            public void onAnimationEnd(Animation animation) {
                                                img_fav.setImageDrawable(mContext.getDrawable(R.drawable.collect_no));
                                                collectBean.is_collect = 0;

                                            }

                                            @Override
                                            public void onAnimationRepeat(Animation animation) {

                                            }
                                        });

                                        img_fav.startAnimation(scaleExit);

                                    }

                                }

                                @Override
                                public void onError(Object tag, Throwable e) {

                                }

                                @Override
                                public void onCancel(Object tag, Throwable e) {

                                }
                            });

                        } else {

                            new api(mContext).addCollect("1", HotelDetailActivity.this.userBean.token, bean.belong, bean.id, new RxStringCallback() {
                                @Override
                                public void onNext(Object tag, String response) {
                                    respon result = new Gson().fromJson(response, new TypeToken<respon>() {
                                    }.getType());

                                    if (result.code.equals("200")) {
                                        //改变星星的状态

                                        ScaleAnimation scaleExit = new ScaleAnimation(1f, 0.5f, 1f, 0.5f);
                                        scaleExit.setDuration(300);

                                        scaleExit.setAnimationListener(new Animation.AnimationListener() {
                                            @Override
                                            public void onAnimationStart(Animation animation) {

                                            }

                                            @Override
                                            public void onAnimationEnd(Animation animation) {
                                                img_fav.setImageDrawable(mContext.getDrawable(R.drawable.collect));
                                                collectBean.is_collect = 1;
                                            }

                                            @Override
                                            public void onAnimationRepeat(Animation animation) {

                                            }
                                        });

                                        img_fav.startAnimation(scaleExit);

                                    }
                                }

                                @Override
                                public void onError(Object tag, Throwable e) {

                                }

                                @Override
                                public void onCancel(Object tag, Throwable e) {

                                }
                            });
                        }
                    }
                }

            }
        });

    }

    @Override
    public void ensureUI() {

        setSupportActionBar(toolbar);
        toolbar.setEnabled(true);

        shareDialog = new ShareDialog(mContext);

        bean = (CommentIntentBean) getIntent().getSerializableExtra("detail");
        strStar = getIntent().getStringExtra("star");

        switch (strStar) {
            case "豪华":
                star = 5;

                break;

            case "高档":
                star = 4;

                break;

            case "舒适":
                star = 3;

                break;

            case "经济":
                star = 2;

                break;
        }

        new api(mContext).getHotelInfo(bean.belong, bean.id, bean.checkIn, bean.checkOut, hotelInfo);

        getWindow().setEnterTransition(initContentEnterTransition());
        getWindow().setReturnTransition(initContentExitTransition());
    }

    private Transition initContentExitTransition() {

        Transition fade = new Fade();

        fade.setDuration(300);

        return fade;
    }

    private Transition initContentEnterTransition() {

        final Fade fade = new Fade();

        fade.addListener(new Transition.TransitionListener() {
            @Override
            public void onTransitionStart(Transition transition) {
                tv_title.setText(bean.keyWord);
            }

            @Override
            public void onTransitionEnd(Transition transition) {
                fade.removeListener(this);
                setStar(star);

                userBean = mApp.getBeanPrefernce(Preferences.LOCAL.USERLOGIN);

                if (userBean != null) {
                    //请求有没有收藏
                    new api(mContext).isCollect(userBean.token, bean.id, bean.belong, collectCallBack);

                } else {

                    img_fav.animate().scaleX(1).scaleY(1).setDuration(300).setDuration(1000).start();

                }
            }

            @Override
            public void onTransitionCancel(Transition transition) {

            }

            @Override
            public void onTransitionPause(Transition transition) {

            }

            @Override
            public void onTransitionResume(Transition transition) {

            }
        });

        return fade;
    }

    private void initView(HotelDetail response) {

        ArrayList<String> bannerList = new ArrayList<>();
        bannerList.addAll(response.pics);

        initBanner(bannerList);
        initTablayout(response);

       /* Transition explode = new Explode();
        explode.setDuration(600);
        explode.setInterpolator(new OvershootInterpolator());
        TransitionManager.beginDelayedTransition(nestedScrollView, explode);*/

        main_content.removeView(pro);

        vp_content.setVisibility(View.VISIBLE);

    }

    private void setStar(int count) {

        if (count == 0) {
            return;
        }

        View view = View.inflate(mContext, R.layout.item_stars, null);

        ll_star_container.addView(view, ll_star_container.getChildCount());

        Animation animation = AnimationUtils.loadAnimation(this, R.anim.star_ani);

        ll_star_container.getChildAt(ll_star_container.getChildCount() - 1).startAnimation(animation);

        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                setStar(--star);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    private void initTablayout(HotelDetail response) {

        ArrayList titleList = new ArrayList();

        titleList.add(mContext.getString(R.string.tab_detail));
        titleList.add(mContext.getString(R.string.tab_comment));
        titleList.add(mContext.getString(R.string.tab_price));

        ArrayList<Fragment> mList = new ArrayList<>();

        InfoFragment infoFragment = new InfoFragment(response, new VPSet() {
            @Override
            public void setVPIndex(int index) {
                vp_content.setCurrentItem(index);
            }
        }, bean.checkIn, bean.checkOut);

        webFragment = new WebFragment(response.third_comment_url);
        PriceFragment priceFragment = new PriceFragment(response.shop, response.rate, bean.checkIn, bean.checkOut, response.title);

        mList.add(infoFragment);
        mList.add(webFragment);
        mList.add(priceFragment);

        MyFragmentAdapter mAdapter = new MyFragmentAdapter(getSupportFragmentManager(), titleList, mList);

        vp_content.setPageTransformer(false, new ScaleXPageTransformer());
        vp_content.setAdapter(mAdapter);
        vp_content.setOffscreenPageLimit(mList.size());
        tabLayout.setupWithViewPager(vp_content, true);

    }

    private void initBanner(ArrayList bannerList) {

       /* Animator animator = ViewAnimationUtils.createCircularReveal(banner,

                banner.getWidth() / 2, banner.getHeight() / 2,
                (int) RudenessScreenHelper.pt2px(mContext, 100), banner.getWidth());

        animator.setInterpolator(new AccelerateDecelerateInterpolator());

        animator.setDuration(600);

        animator.start();
*/
        //设置banner的indicator样式
        banner.setBannerStyle(BannerConfig.NUM_INDICATOR);

        //设置图片加载器
        banner.setImageLoader(new FloImageLoader());

        //设置图片
        banner.setImages(bannerList);

        //设置banner动画效果
        banner.setBannerAnimation(Transformer.Accordion);

        //设置自动轮播
        banner.isAutoPlay(false);

        //设置指示器位置
        banner.setIndicatorGravity(BannerConfig.RIGHT);

        banner.start();

        tv_title.setTextColor(Color.WHITE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleMessageEvent(DafultMessageEvent message) {
        switch (message.TAG) {

            case "LoginActivity":

                userBean = mApp.getBeanPrefernce(Preferences.LOCAL.USERLOGIN);
                new api(mContext).isCollect(userBean.token, bean.id, bean.belong, collectCallBack);

                break;
        }
    }

    private RxResultCallback hotelInfo = new RxResultCallback<HotelDetail>() {
        @Override
        public void onNext(Object tag, int code, String message, HotelDetail response) {

            if (code == 200) {
                initView(response);

                share_url = response.share_url;

                if (response.pics != null){

                    shared_img_url = response.pics.get(0);

                }

                img_share.animate().scaleX(1).scaleY(1).setDuration(300).setDuration(1000).start();
            }
        }

        @Override
        public void onError(Object tag, Throwable e) {

        }

        @Override
        public void onCancel(Object tag, Throwable e) {

        }

    };

    private RxResultCallback<Comment> collectCallBack = new RxResultCallback<Comment>() {
        @Override
        public void onNext(Object tag, int code, String message, Comment response) {

            if (code == 200) {

                img_fav.setEnabled(true);

                collectBean = response;

                if (collectBean.is_collect == 0) {
                    img_fav.setImageDrawable(mContext.getDrawable(R.drawable.collect_no));
                    img_fav.animate().scaleX(1).scaleY(1).setStartDelay(300).setDuration(1000).setInterpolator(new OvershootInterpolator()).start();

                } else {

                    img_fav.setImageDrawable(mContext.getDrawable(R.drawable.collect));
                    img_fav.animate().scaleX(1).scaleY(1).setStartDelay(300).setDuration(1000).setInterpolator(new OvershootInterpolator()).start();
                }

            } else {

                img_fav.setEnabled(false);
            }
        }

        @Override
        public void onError(Object tag, Throwable e) {

            img_fav.setEnabled(false);
        }

        @Override
        public void onCancel(Object tag, Throwable e) {

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }

    @Override
    public void finish() {

        super.finish();
    }
}
